package edu.avans.hartigehap.service.jpa;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;

import edu.avans.hartigehap.domain.WebMail;
import edu.avans.hartigehap.service.WebMailService;

public class WebMailServiceImpl implements WebMailService {

	@Autowired
	private WebMail webmail;

	public void sendMail(String email) {
		webmail = new WebMail();
		String[] destAddr = {email};

		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.port", "587");

		Session session = Session.getInstance(props,
				new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(
						webmail.getUsername(), webmail.getPassword());
			}
		});

		try {
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress(webmail.getFromAddr()));
			message.setRecipients(MimeMessage.RecipientType.CC,
					InternetAddress.parse("hartigeorders@gmail.com"));
			message.setSubject("Nieuwe bestelling Hartige Hap");
			message.setText("Geachte klant,\n\n"
					+ "Uw bestelling is geplaatst. \n\n"
					+ "mvg,\n" + "De Hartige Hap");

			Transport.send(message);

			// actual mail to customer
			InternetAddress[] addressTo = new InternetAddress[destAddr.length];
			for (int i = 0; i < destAddr.length; i++) {
				addressTo[i] = new InternetAddress(destAddr[i]);
			}
			message.setRecipients(MimeMessage.RecipientType.TO, addressTo);
			Transport.send(message);

		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}